﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using GmailMetroNotifier.Client.Properties;

namespace GmailMetroNotifier.Client.Common
{
    /// <summary>
    /// Helper class to assist in XML-related operations.
    /// </summary>
    public static class XHelper
    {
        /// <summary>
        /// Gets the value of the first element with the given local name (no xmlns) in the specified
        /// document.
        /// </summary>
        /// <typeparam name="TValue">The type of the value to be returned.</typeparam>
        /// <param name="document">The document where the element is to be searched for.</param>
        /// <param name="elementName">The local name of the element to be searched for.</param>
        /// <returns>The value of the element if found, or the type default value otherwise.</returns>
        /// <exception cref="ArgumentNullException">Thrown when either the document or the element name is null.</exception>
        /// <exception cref="ArgumentException">Thrown when the element name is empty.</exception>
        public static TValue GetElementValue<TValue>(XDocument document, string elementName)
        {
            if (document == null)
            {
                throw new ArgumentNullException("document");
            }

            if (elementName == null)
            {
                throw new ArgumentNullException("elementName");
            }

            if (elementName.Trim().Length == 0)
            {
                throw new ArgumentException(Resources.EXCEPTION_MSG_ARGUMENT_EXCEPTION, "elementName");
            }

            TValue value = default(TValue);

            XElement xElement = document.Root.Descendants()
                .FirstOrDefault(e => e.Name.LocalName.Equals(elementName, StringComparison.OrdinalIgnoreCase));

            if (xElement != null && !string.IsNullOrWhiteSpace(xElement.Value))
            {
                value = (TValue)Convert.ChangeType(xElement.Value, typeof(TValue), CultureInfo.InvariantCulture);
            }

            return value;
        }
    }
}
